# 15. 图像物体的边界

15 15-1

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

const lines = [];
let linecount = [];
let n,m,mp,visited,count  = 0;
const dx = [-1, -1, -1, 0, 1, 1, 1, 0];
const dy = [-1, 0, 1, 1, 1, 0, -1, -1];
function dfs (x,y,mp,n,m,visited) {
    visited[x][y] = true;
    for(let i=0; i<8; i++) {
        const nx = x + dx[i];
        const ny = y + dy[i];
        if (nx >=0 && nx<n && ny>=0 && ny<m && mp[nx][ny]===1 && isBorder(nx, ny, mp, n, m) && !visited[nx][ny]) {
            dfs(nx, ny, mp, n, m, visited);
        }
    }
}
function isBorder(x,y,mp,n,m) {
    for(let i=0; i<8; i++) {
        const nx = x + dx[i];
        const ny = y + dy[i];
        if (nx>=0 && nx<n && ny>=0 && ny<m && mp[nx][ny] === 5) {
            return true;
        }
    }
    return false;
}
rl.on('line', (line) => {
    lines.push(line);
    lineCount++;
    if (lineCount === 1) {
        [n,m] = lines[0].split(' ').map(Number);
    } else if (lineCount <= n + 1) {
        if (lineCount === 2) {
            mp = new Array(n);
            visited = new Array(n);
        }
        mp[lineCount - 2] = lines[lineCount - 1].split(' ').map(Number);
        visited[lineCount - 2] = new Array(m).fill(false);
    }
    if (lineCount === n+1) {
        for(let i=0; i<n ; i++) {
            for(let j=0; j<m; j++) {
                if (mp[i][j] === 1 && isBorder(i,j,mp,n,m) && !visited[i][j]) {
                    dfs(i,j,mp,n,m,visited);
                    count++;
                }
            }
        }
        console.log(count);
    }
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56